In [1]:
#KUTUPHANELER
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import os
import re
import string
import random

import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
from tensorflow.keras.layers.experimental.preprocessing import TextVectorization
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Embedding, Dense


from sklearn import metrics
from sklearn.metrics import confusion_matrix
from sklearn.model_selection import train_test_split



import warnings
warnings.filterwarnings('ignore')
try:
    import gradio as gr
except:
    !pip install gradio --quiet
In [2]:
#DEĞİŞKENLER
embed_dim = 16 
feed_forward_dim = 64 
min_review_size=15
max_review_size=40
batch_size=64

#STOPWORDS TURKCE LİSTE TANIMLAMA
tr_stop_words=['fakat','lakin','ancak','acaba', 'ama', 'aslında', 'az', 'bazı', 'belki', 'biri', 'birkaç', 'birşey', 'biz', 'bu', 'çok', 'çünkü', 'da', 'daha', 'de', 'defa', 'diye', 'eğer', 'en', 'gibi', 'hem', 'hep', 'hepsi', 'her', 'hiç', 'için', 'ile', 'ise', 'kez', 'ki', 'kim', 'mı', 'mu', 'mü', 'nasıl', 'ne', 'neden', 'nerde', 'nerede', 'nereye', 'niçin', 'niye', 'o', 'sanki', 'şey', 'siz', 'şu', 'tüm', 've', 'veya', 'ya', 'yani']
In [3]:
#FONKSİYONLAR
@tf.keras.utils.register_keras_serializable()
def custom_standardization(input_string):   
    no_uppercased = tf.strings.lower(input_string, encoding='utf-8')
    no_stars = tf.strings.regex_replace(no_uppercased, "\*", " ")
    no_repeats = tf.strings.regex_replace(no_stars, "devamını oku", "")    
    no_html = tf.strings.regex_replace(no_repeats, "<br />", "")
    no_digits = tf.strings.regex_replace(no_html, "\w*\d\w*","")
    no_punctuations = tf.strings.regex_replace(no_digits, f"([{string.punctuation}])", r" ")    
    no_extra_space = tf.strings.regex_replace(no_punctuations, " +"," ")   
    no_I = tf.strings.regex_replace(no_extra_space, "ı","i")
    no_O = tf.strings.regex_replace(no_I, "ö","o")
    no_C = tf.strings.regex_replace(no_O, "ç","c")
    no_S = tf.strings.regex_replace(no_C, "ş","s")
    no_G = tf.strings.regex_replace(no_S, "ğ","g")
    no_U = tf.strings.regex_replace(no_G, "ü","u")
    return no_U

def prepare_lm_inputs_labels(text):
    text = tf.expand_dims(text, -1) 
    return tf.squeeze(vectorize_layer(text))

def create_model_FFN():
    inputs_tokens = layers.Input(shape=(max_len,), dtype=tf.int32)
    embedding_layer = layers.Embedding(input_dim=vocab_size, 
                                       output_dim=embed_dim, 
                                       input_length=max_len)
    x = embedding_layer(inputs_tokens)
    x = layers.Flatten()(x)
    dense_layer = layers.Dense(feed_forward_dim, activation='relu')
    x = dense_layer(x)
    x = layers.Dropout(.5)(x)
    outputs = layers.Dense(32)(x)

    model = keras.Model(inputs=inputs_tokens, outputs=outputs, name='model_FFN')
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    metric_fn  = tf.keras.metrics.SparseCategoricalAccuracy()
    model.compile(optimizer="adam", loss=loss_fn, metrics=metric_fn)  
    return model

def create_model_Conv1D():
    inputs_tokens = layers.Input(shape=(max_len,), dtype=tf.int32)
    embedding_layer = layers.Embedding(input_dim=vocab_size, 
                                       output_dim=embed_dim, 
                                       input_length=max_len)
    x = embedding_layer(inputs_tokens)
    x = layers.Conv1D(filters=256, kernel_size=7, 
                      padding='same', activation='relu')(x)   
    x = layers.Conv1D(filters=128, kernel_size=5, 
                      padding='same', activation='relu')(x)
    x = layers.Conv1D(filters=128, kernel_size=3, 
                      padding='same', activation='relu')(x)
    x = layers.MaxPooling1D(pool_size=2)(x)    
    x = layers.Flatten()(x)
    x = layers.Dense(feed_forward_dim, activation='sigmoid')(x)
    x = layers.Dropout(0.5)(x)
    outputs = layers.Dense(32)(x)
    model = keras.Model(inputs=inputs_tokens, 
                        outputs=outputs, name='model_Conv1D')
    loss_fn = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
    metric_fn  = tf.keras.metrics.SparseCategoricalAccuracy()
    model.compile(optimizer="adam", loss=loss_fn, metrics=metric_fn)    
    return model

def classify(text):
    pred1=E2E_CONV1D.predict([text])
    pred2= E2E_FFN.predict([text])
    sonuc='CONV1D : ' + id_to_category[np.argmax(pred1)] + '\nFFN : ' + id_to_category[np.argmax(pred2)]
    return sonuc
In [4]:
#VERİYİ ALMA DF OLUŞTURMA
df=pd.read_csv('ticaret-yorum.csv')
pd.set_option('max_colwidth',400)
In [5]:
df.head(5)
Out[5]:
category text
0 alisveris Altus Hırdavat Yapı Malzemeleri Drone Diye Kargodan Lastik Ayakkabı Çıktı,"Instagram'da dolanırken sponsorlu bir bağlantı gördüm. Drone satışı yapılıyor. Normalde böyle şeylere inanmam ancak takipçi sayısının fazla olması, numaralarının olması, ödemeyi peşin değil karşı ödemeli ödenmesi, fotoğraflara yapılan yorumlar vs... Az da olsa güvenerek ben de sipariş vermek istedim...Devamını oku"
1 alisveris Albay Bilgisayar Garanti Yalanı İle Yanılttı,Garanti kapsamında yer alan  Casper bilgisayarım garanti belgesi ile birlikte İzmit Casper bilgisayar yetkili servisine albay bilgisayara bıraktım. Önce almak istemedi uzun ikna cabası ve uğraş sonunda zorla garanti dahiline bıraktım bilgisayar açılmıyordu. Sonrasında ertesi gün bilgisayarın yapıldı...Devamını oku
2 alisveris Okyanus Petshop Ürün İade Sorunu!,Satıcıdan GittiGidiyor üzerinden 385 TL tutarında Frolicat Interactive Kedi Lazer oyuncağı satın aldım. Ürünü açıp bir kez çalıştırdığımda çok gürültü çıkardığını fark ettim ve ürünü iade etmeye karar verdim. Hatam iade sürecinin 14 gün içinde olması gerektiğini bilmemekti. Ürünü teslim aldıktan son...Devamını oku
3 alisveris Anda İhtiyaç Ve Tüketim Maddeleri Knee Tork Dizlik Esnemiyor!,Anda ihtiyaç ve tüketim maddeleri pazarlama san. Lim. Şti. Den 139 TL kapıda teslim knee tork adlı ürünü satın aldım. Ürün 0815774588452 takip no... İle Aras Kargo tarafından tarafıma teslim edildi. Ürün kargoya firma tarafından 26.05.2020 tarihinde kargoya verilmiş. Ürünün üst dizlik bedeni bacağım...Devamını oku
4 alisveris BB Kargo Dağıtım'dan Aldığım Ürün Bozuk Çıktı Ve Muhatap Bulamıyorum!,Fotoğrafını göndermiş olduğum ürünün kablosunda temassızlık var ve ne fatura ne numara sadece gönderen kargonun adı var ve onlara da ulaşamıyorum ayrıca kargo daha bugün elime geçti Denizli Marmaris gezmiş ürün. Beni arayan numarayı buldum ona da ulaşılamıyor.Devamını oku
In [6]:
df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 431306 entries, 0 to 431305
Data columns (total 2 columns):
 #   Column    Non-Null Count   Dtype 
---  ------    --------------   ----- 
 0   category  431306 non-null  object
 1   text      431306 non-null  object
dtypes: object(2)
memory usage: 6.6+ MB
In [7]:
df.isnull().sum()
Out[7]:
category    0
text        0
dtype: int64
In [8]:
df.describe(include='all').T
Out[8]:
count unique top freq
category 431306 32 kamu-hizmetleri 14009
text 431306 427231 Akman Nikah Ve Balo Salonu Sözleşme Bedeli Kapora İadesi Yapmıyor,20.07.2019 tarihinde 13.06.2020 tarihli kına gecesi için Sincan harikalar diyarı akman prestij salonuna kapora bedeli 2600 TL ödeyerek anlaşma yaptık. Korona virüsü nedeniyle iptal etmek için mayıs ayından itibaren defalarca görüştüm ve sonra dilekçe verdim sözlü olarak kapora bedeli ödenmez ama dil...Devamını oku 154
In [9]:
#tekrar eden unique olmayan değerleri silme komutu
df.drop_duplicates(subset="text", keep="first", inplace=True, ignore_index=True)
In [10]:
df.describe(include='all').T
Out[10]:
count unique top freq
category 427231 32 kamu-hizmetleri 13998
text 427231 427231 Altus Hırdavat Yapı Malzemeleri Drone Diye Kargodan Lastik Ayakkabı Çıktı,"Instagram'da dolanırken sponsorlu bir bağlantı gördüm. Drone satışı yapılıyor. Normalde böyle şeylere inanmam ancak takipçi sayısının fazla olması, numaralarının olması, ödemeyi peşin değil karşı ödemeli ödenmesi, fotoğraflara yapılan yorumlar vs... Az da olsa güvenerek ben de sipariş vermek istedim...Devamını oku" 1
In [11]:
topic_list=df.category.unique()
In [12]:
number_of_topics=len(topic_list)
In [13]:
number_of_categories=number_of_topics
In [14]:
df.category.value_counts()
Out[14]:
kamu-hizmetleri              13998
cep-telefon-kategori         13975
enerji                       13968
finans                       13958
ulasim                       13943
medya                        13908
kargo-nakliyat               13877
mutfak-arac-gerec            13867
alisveris                    13816
mekan-ve-eglence             13807
elektronik                   13770
beyaz-esya                   13761
kucuk-ev-aletleri            13732
giyim                        13676
internet                     13657
icecek                       13564
saglik                       13559
sigortacilik                 13486
spor                         13448
mobilya-ev-tekstili          13434
otomotiv                     13377
turizm                       13317
egitim                       13264
gida                         13150
temizlik                     13111
mucevher-saat-gozluk         12964
bilgisayar                   12963
kisisel-bakim-ve-kozmetik    12657
anne-bebek                   12381
emlak-ve-insaat              12024
hizmet-sektoru               11463
etkinlik-ve-organizasyon     11356
Name: category, dtype: int64
In [15]:
df.category.value_counts().plot.bar(x="Topics", y="Number of Reviews", figsize=(32,8))
Out[15]:
<Axes: >
In [16]:
df['words']=[len(x.split()) for x in df['text'].tolist()]
In [17]:
df[['words','text']].head()
Out[17]:
words text
0 49 Altus Hırdavat Yapı Malzemeleri Drone Diye Kargodan Lastik Ayakkabı Çıktı,"Instagram'da dolanırken sponsorlu bir bağlantı gördüm. Drone satışı yapılıyor. Normalde böyle şeylere inanmam ancak takipçi sayısının fazla olması, numaralarının olması, ödemeyi peşin değil karşı ödemeli ödenmesi, fotoğraflara yapılan yorumlar vs... Az da olsa güvenerek ben de sipariş vermek istedim...Devamını oku"
1 44 Albay Bilgisayar Garanti Yalanı İle Yanılttı,Garanti kapsamında yer alan  Casper bilgisayarım garanti belgesi ile birlikte İzmit Casper bilgisayar yetkili servisine albay bilgisayara bıraktım. Önce almak istemedi uzun ikna cabası ve uğraş sonunda zorla garanti dahiline bıraktım bilgisayar açılmıyordu. Sonrasında ertesi gün bilgisayarın yapıldı...Devamını oku
2 47 Okyanus Petshop Ürün İade Sorunu!,Satıcıdan GittiGidiyor üzerinden 385 TL tutarında Frolicat Interactive Kedi Lazer oyuncağı satın aldım. Ürünü açıp bir kez çalıştırdığımda çok gürültü çıkardığını fark ettim ve ürünü iade etmeye karar verdim. Hatam iade sürecinin 14 gün içinde olması gerektiğini bilmemekti. Ürünü teslim aldıktan son...Devamını oku
3 53 Anda İhtiyaç Ve Tüketim Maddeleri Knee Tork Dizlik Esnemiyor!,Anda ihtiyaç ve tüketim maddeleri pazarlama san. Lim. Şti. Den 139 TL kapıda teslim knee tork adlı ürünü satın aldım. Ürün 0815774588452 takip no... İle Aras Kargo tarafından tarafıma teslim edildi. Ürün kargoya firma tarafından 26.05.2020 tarihinde kargoya verilmiş. Ürünün üst dizlik bedeni bacağım...Devamını oku
4 48 BB Kargo Dağıtım'dan Aldığım Ürün Bozuk Çıktı Ve Muhatap Bulamıyorum!,Fotoğrafını göndermiş olduğum ürünün kablosunda temassızlık var ve ne fatura ne numara sadece gönderen kargonun adı var ve onlara da ulaşamıyorum ayrıca kargo daha bugün elime geçti Denizli Marmaris gezmiş ürün. Beni arayan numarayı buldum ona da ulaşılamıyor.Devamını oku
In [18]:
df['words'].describe()
Out[18]:
count    427231.000000
mean         44.408624
std           8.108499
min           2.000000
25%          42.000000
50%          46.000000
75%          49.000000
max         183.000000
Name: words, dtype: float64
In [19]:
df.groupby(['category'])['words'].describe()
Out[19]:
count mean std min 25% 50% 75% max
category
alisveris 13816.0 43.562970 8.607092 4.0 41.0 45.0 49.0 63.0
anne-bebek 12381.0 44.833131 7.238100 3.0 42.0 46.0 49.0 62.0
beyaz-esya 13761.0 45.227091 7.409185 4.0 43.0 47.0 50.0 67.0
bilgisayar 12963.0 44.252796 8.119548 3.0 42.0 46.0 49.0 95.0
cep-telefon-kategori 13975.0 43.848229 8.071967 5.0 41.0 45.0 49.0 64.0
egitim 13264.0 43.345371 7.985817 4.0 41.0 45.0 48.0 68.0
elektronik 13770.0 44.029920 8.270702 3.0 41.0 46.0 49.0 64.0
emlak-ve-insaat 12024.0 44.880073 8.079509 3.0 42.0 47.0 50.0 66.0
enerji 13968.0 44.903780 8.640223 4.0 42.0 46.0 50.0 183.0
etkinlik-ve-organizasyon 11356.0 42.752378 9.205907 3.0 40.0 45.0 49.0 150.0
finans 13958.0 43.579453 8.548767 4.0 41.0 45.0 49.0 64.0
gida 13150.0 43.980380 7.865412 4.0 41.0 45.0 49.0 73.0
giyim 13676.0 43.476821 8.168650 4.0 41.0 45.0 48.0 64.0
hizmet-sektoru 11463.0 44.175085 8.598144 4.0 42.0 46.0 49.0 64.0
icecek 13564.0 44.048953 8.122139 4.0 41.0 46.0 49.0 64.0
internet 13657.0 43.888189 8.556235 4.0 41.0 46.0 49.0 65.0
kamu-hizmetleri 13998.0 45.440706 8.231393 3.0 43.0 47.0 50.0 68.0
kargo-nakliyat 13877.0 43.958853 8.357877 4.0 42.0 46.0 49.0 66.0
kisisel-bakim-ve-kozmetik 12657.0 44.203998 7.788059 4.0 41.0 46.0 49.0 145.0
kucuk-ev-aletleri 13732.0 44.591320 7.682404 4.0 42.0 46.0 49.0 66.0
medya 13908.0 43.688381 7.900280 3.0 41.0 45.0 48.0 73.0
mekan-ve-eglence 13807.0 44.737017 7.747632 3.0 42.0 46.0 49.0 67.0
mobilya-ev-tekstili 13434.0 45.100194 7.504440 4.0 43.0 46.0 50.0 98.0
mucevher-saat-gozluk 12964.0 45.701790 7.466333 6.0 44.0 47.0 50.0 68.0
mutfak-arac-gerec 13867.0 44.854907 7.327408 4.0 42.0 46.0 49.0 66.0
otomotiv 13377.0 45.561262 7.884246 4.0 43.0 47.0 50.0 63.0
saglik 13559.0 46.453426 7.202856 4.0 44.0 48.0 51.0 65.0
sigortacilik 13486.0 44.206955 7.793304 2.0 42.0 46.0 49.0 65.0
spor 13448.0 44.804655 8.732219 4.0 43.0 47.0 50.0 147.0
temizlik 13111.0 43.075662 8.703712 3.0 40.0 45.0 49.0 93.0
turizm 13317.0 45.050687 8.378730 4.0 43.0 47.0 50.0 64.0
ulasim 13943.0 44.656745 7.730242 4.0 42.0 46.0 49.0 66.0
In [20]:
df[df['words']<min_review_size].count()
Out[20]:
category    4950
text        4950
words       4950
dtype: int64
In [21]:
df[df['words']<min_review_size]
Out[21]:
category text words
143 alisveris Vatan Bilgisayar Kargo Hakkında Bilgi Verilmemesi Çağrı Merkezinin 30 Dakika Bekletmesi,"02.05.2020 tarihinde verdiğim 13
146 alisveris A101 Sipariş Alıyor Ancak Getirmiyor,"28.05.2020 Tarihinde sipariş verdim. 8
198 alisveris Boyner Eksik Ürün Gönderme,"Merhabalar 4
206 alisveris Tekzen 40 Gündür Ücret İadesi Yapılmıyor,"17.04.2020 tarihinde jaluzi perde siparişi verdim. Sipariş numaram: 636576660 14
228 alisveris Boyner Sipariş 1 Haftadır Tedarik Sürecinde!,"Merhabalar, 6
... ... ... ...
426760 ulasim Pegasus Uçuşu İptal Etti!,"13.02.2020 diyarbakır'dan istanbul sabiha gökcen havalimanına 21.25 uçuşumuz vardı. 12
426779 ulasim Kent Kart'a FastPay İle Yaptığım Yükleme Hesabıma Geçmedi!,"13/02/2020 Tarihinde Denizbank'ın FastPay uygulaması vasıtasıyla 13
426922 ulasim Efe Tur İnternet Yok,"İnternet şifresi istiyoruz kota doluyor veremeyiz diyorlar televizyonlar açılmıyor 12
427020 ulasim Efe Tur'da Saygısızlık, İhmalkarlık!,"11.02.2020 20:00 Ankara İstanbul seferini yapan 210 numaralı aracın şoförü 13
427211 ulasim Pegasus  Koltuk Numarası Değişimi  ve Kırık Valiz," 7

4950 rows × 3 columns

In [22]:
df=df[df['words']>=min_review_size]
In [23]:
df.count()
Out[23]:
category    422281
text        422281
words       422281
dtype: int64
In [24]:
vocab=set()
corpus=[x.split() for x in df['text'].tolist()]
for sentence in corpus:
    for word in sentence:
        vocab.add(word.lower())
print("Ham verilerdeki farklı kelime sayısı: ", len(vocab))
Ham verilerdeki farklı kelime sayısı:  900327
In [25]:
list(vocab)[:25]
Out[25]:
['ücreti,kargonun',
 'sağlanamadı.arıyoruz',
 'duyurulmuştu',
 'mesafelerinin',
 'alamıyoruz!,"kocaeli',
 '02542596devamını',
 'hazardağlı',
 'mecbure...devamını',
 'tekniği!,3',
 'aparatında',
 'toksik',
 'opay',
 'yanılttı,kts',
 "asansör'de",
 'basitinden',
 'erkenez',
 'yollamıyor,"1006****16',
 'hafta-on',
 'çıkmaz)',
 'yanıltması,"11',
 'k-5002',
 '35*45',
 'gazdamı',
 'sorunu!,"bartın',
 'silinmeler']
In [26]:
word_freq=df.text.str.split(expand=True).stack().value_counts()
word_freq=word_freq.reset_index(name='freq').rename(columns={'index': 'word'})
In [27]:
top_50_frequent_words=word_freq[:50]
top_50_frequent_words
Out[27]:
word freq
0 bir 289644
1 oku 267115
2 ve 254044
3 için 131232
4 bu 121281
5 oku" 115391
6 de 100804
7 da 82413
8 ama 69900
9 ile 67040
10 gün 66605
11 sonra 63337
12 ne 62226
13 2 60658
14 1 59747
15 rağmen 59114
16 önce 57862
17 tarihinde 56601
18 çok 56273
19 TL 55908
20 kadar 54177
21 daha 53622
22 ay 50605
23 sipariş 47781
24 diye 44581
25 olarak 43819
26 aldığım 43557
27 hala 42698
28 Bu 42371
29 3 41178
30 gibi 40698
31 ürün 38794
32 iptal 38410
33 yok 36892
34 ...Devamını 36162
35 var 36103
36 müşteri 35149
37 hiçbir 34673
38 fakat 34542
39 iade 33598
40 Ve 32270
41 aldım 31839
42 her 31464
43 şekilde 31133
44 olan 31084
45 saat 30228
46 aldım. 30182
47 Bir 30182
48 teslim 30137
49 bana 30119
In [28]:
for each in top_50_frequent_words['word']:
    if each in tr_stop_words:
        print(each)
ve
için
bu
de
da
ama
ile
ne
çok
daha
diye
gibi
fakat
her
In [29]:
df=df.sample(frac=1)
In [30]:
df["category"]=df["category"].astype('category')
df.dtypes
Out[30]:
category    category
text          object
words          int64
dtype: object
In [31]:
df["category_id"]=df["category"].cat.codes
df.tail()
Out[31]:
category text words category_id
73236 egitim D&R Eksik Ürün Teslimi,11.04.2020 tarihinde internet siteniz üzerinden ürün siparişinde bulundum ve bugün elime ulaşan kargoda eksik ürün mevcut. İletişim kurmaya çalıştım fakat hiçbir dönüt alamadım. Sorunumla bir an önce ilgilenilmesini talep ediyorum. Sipariş Numarası: W182810941.Devamını oku 37 5
161172 giyim Yalı Spor Siparişlerim Bir Türlü Kargoya Verilmedi,Şikayetlerin hepsi son 15 gün içinde girilmiş ve hiçbirine cevap vermiyorlar adamlar o kadar rahat ki ne bir telefon ne çağrı merkezi hiçbir şekilde ulaşamıyoruz. İflas ettiler galiba... Umarım tez zamanda layığınızı bulursunuz. Başkada bir sözüm yok.Devamını oku 44 12
81375 elektronik Grundig Verdiğim Paraya Yazık,"TV hızı kötü , Netflix gibi dünya çapında olan ve neredeyse her TV de olan uygulama burda yok. Söylenen ise anlaşmamız yok gibi saçmalık. Destek zaten kötü bir konuşmaya sahip.  Gidin 100 liraya tüplü TV alın aynı işlevler var.  Devamını oku" 44 6
237913 kargo-nakliyat Sürat Kargo Ürünüm Hala Tarafıma Teslim Edilmedi!,"Ürün satın aldığım firma ürünü Sürat Kargo'ya teslim etmesine rağmen 4 gündür aynı dağıtım şubesinde beklemesi, şubenin telefonları 10 kez aramama rağmen açmaması ve müşteri hizmetlerine şikayet etmeme rağmen herhangi bir netice alamadım. Bir çok kez de aynı sorunu yaşadım. 10 lira pahalı olsun ama ...Devamını oku" 53 17
142053 finans Bitexen İkametgahım Onay Bekliyor Ne Yapmalıyım Ne Zaman Onaylanacak Bilgi,Yan yana arkadaşım ile yapmış olduğumuz üyelik işlemlerinde arkadaşımın üyeliği doğrulandı. Şahsımınki onay bekliyor. Canlı desteğe yazmama rağmen dönüş yapılmadı. Şahsıma acil3n dönüş yapılmasını istiyorum. Ha**********@hotmail.com mail adresim ismim mehmet gümüşDevamını oku 41 10
In [32]:
id_to_category=pd.Series(df.category.values, index=df.category_id).to_dict()
In [33]:
category_to_id={v:k for k,v in id_to_category.items()}
In [34]:
features, targets = df['text'],df['category_id']

all_train_features, test_features, all_train_targets, test_targets= train_test_split(
        features, targets,
        train_size=0.8,
        test_size=0.2,
        random_state=42,
        shuffle= True,
        stratify=targets
)
In [35]:
print("All Train Data Set size: ",len(all_train_features))
print("Test Data Set size: ",len(test_features))
All Train Data Set size:  337824
Test Data Set size:  84457
In [36]:
reduce_ratio = 0.05

reduced_train_features, _, reduced_train_targets, _ = train_test_split(
        all_train_features, all_train_targets,
        train_size=reduce_ratio,
        random_state=42,
        shuffle = True,
        stratify=all_train_targets
    )
In [37]:
print("Reduced Train Data Set size: ",len(reduced_train_features))
print("Test Data Set size: ",len(test_features))
Reduced Train Data Set size:  16891
Test Data Set size:  84457
In [38]:
train_features, val_features, train_targets, val_targets = train_test_split(
        reduced_train_features, reduced_train_targets,
        train_size=0.9,
        random_state=42,
        shuffle = True,
        stratify=reduced_train_targets
    )
In [39]:
print("Train Data Set size: ",len(train_features))
print("Validation Data Set size: ",len(val_features))
print("Test Data Set size: ",len(test_features))
Train Data Set size:  15201
Validation Data Set size:  1690
Test Data Set size:  84457
In [40]:
train_text_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(train_features.values, tf.string)
) 
In [41]:
train_cat_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(train_targets.values, tf.int64),

) 
In [42]:
vocab_size = 100000  
max_len = max_review_size  
In [43]:
vectorize_layer = TextVectorization(
    standardize=custom_standardization,
    max_tokens=vocab_size - 1,
    output_mode="int", 
    output_sequence_length=max_len,
)
In [44]:
vectorize_layer.adapt(train_text_ds_raw)
vocab = vectorize_layer.get_vocabulary()  
In [45]:
print("vocab has the ", len(vocab)," entries")
print("vocab has the following first 10 entries")
for word in range(10):
  print(word, " represents the word: ", vocab[word])
print("2 sample text preprocessing:")
for X in train_text_ds_raw.take(2):
  print(" Given raw data: " )
  print(X.numpy().decode("utf-8") )
  tokenized = vectorize_layer(tf.expand_dims(X, -1))
  print(" Tokenized and Transformed to a vector of integers: " )
  print (tokenized)
  print(" Text after Tokenized and Transformed: ")
  transformed = ""
  for each in tf.squeeze(tokenized):
    transformed= transformed+ " "+ vocab[each]
  print(transformed)  
vocab has the  59228  entries
vocab has the following first 10 entries
0  represents the word:  
1  represents the word:  [UNK]
2  represents the word:  bir
3  represents the word:  ve
4  represents the word:  bu
5  represents the word:  icin
6  represents the word:  de
7  represents the word:  da
8  represents the word:  yok
9  represents the word:  ama
2 sample text preprocessing:
 Given raw data: 
Mars Athletic Club-Macfit 1 Aylık Ücret Aldatması!,"Ankamall Macfit'e 6 aylık üye oldum. Acil iş gereği kayıt olduğum ertesi günü iptal ettirmek istedim. 1 ay kesinti yapacaklarını söylediler bende kabul ettim şu an aylık 97,41 TL kesinti oluyor 61,5 TL geri iade ediyor. Bir aylık ücretiniz 215,46 TL mi? Bu kadar aldatma sizin gibi bir firmaya yakışı...Devamını oku"
 Tokenized and Transformed to a vector of integers: 
tf.Tensor(
[[  493   559   336   219   217   110 28495  4564   219    96   217   444
    210   353   123  1550   315    73   703    86    30  1765   156    25
    883  2859   130   277   220    91    32   129   217    12   883   274
     12    51    33   271]], shape=(1, 40), dtype=int64)
 Text after Tokenized and Transformed: 
 mars athletic club macfit aylik ucret aldatmasi ankamall macfit e aylik uye oldum acil is geregi kayit oldugum ertesi gunu iptal ettirmek istedim ay kesinti yapacaklarini soylediler bende kabul ettim su an aylik tl kesinti oluyor tl geri iade ediyor
 Given raw data: 
Atasun Optik Lens Sipariş Verdim Bir Buçuk Aydır Gelmedi!,Emaar Atasun Optik'ten 01/12/2018 tarihinde dört kutu kontak lens siparişi verdim bir buçuk aydır gelmiyor. Bundan daha önce de lens siparişi vermiştim fakat ilk defa böyle bir sorunla karşılaşıyorum. İlk iki hafta tamam dedim gelmesi zaman alıyordur vs... İki hafta sonra AVM ye gittiğimde mağazaya ...Devamını oku
 Tokenized and Transformed to a vector of integers: 
tf.Tensor(
[[  460   393  2661    19    85     2   895   146    97  4950   460   393
    255    24  2069   734 11855  2661   162    85     2   895   146   479
    514    13    21     6  2661   162  1577    37    67   167    47     2
   1858  2894    67    70]], shape=(1, 40), dtype=int64)
 Text after Tokenized and Transformed: 
 atasun optik lens siparis verdim bir bucuk aydir gelmedi emaar atasun optik ten tarihinde dort kutu kontak lens siparisi verdim bir bucuk aydir gelmiyor bundan daha once de lens siparisi vermistim fakat ilk defa boyle bir sorunla karsilasiyorum ilk iki
In [46]:
train_text_ds = train_text_ds_raw.map(prepare_lm_inputs_labels, 
                                  num_parallel_calls=tf.data.experimental.AUTOTUNE)
In [47]:
train_text_ds.element_spec
Out[47]:
TensorSpec(shape=<unknown>, dtype=tf.int64, name=None)
In [48]:
for each in train_text_ds.take(1):
  print(each)
tf.Tensor(
[  493   559   336   219   217   110 28495  4564   219    96   217   444
   210   353   123  1550   315    73   703    86    30  1765   156    25
   883  2859   130   277   220    91    32   129   217    12   883   274
    12    51    33   271], shape=(40,), dtype=int64)
In [49]:
train_ds = tf.data.Dataset.zip(
    (       train_text_ds,
            train_cat_ds_raw
        )
) 
In [50]:
train_ds.element_spec
Out[50]:
(TensorSpec(shape=<unknown>, dtype=tf.int64, name=None),
 TensorSpec(shape=(), dtype=tf.int64, name=None))
In [51]:
for X,y in train_ds.take(1):
  print("X.shape: ",X.shape, "y.shape: ", y.shape)
  print("X: ", X)
  print("y: ", y)
  input = " ".join([vocab[_] for _ in np.squeeze(X)])
  output = id_to_category[y.numpy()]
  print("input (review as text): " , input)
  print("output (category as text): " , output)
X.shape:  (40,) y.shape:  ()
X:  tf.Tensor(
[  493   559   336   219   217   110 28495  4564   219    96   217   444
   210   353   123  1550   315    73   703    86    30  1765   156    25
   883  2859   130   277   220    91    32   129   217    12   883   274
    12    51    33   271], shape=(40,), dtype=int64)
y:  tf.Tensor(28, shape=(), dtype=int64)
input (review as text):  mars athletic club macfit aylik ucret aldatmasi ankamall macfit e aylik uye oldum acil is geregi kayit oldugum ertesi gunu iptal ettirmek istedim ay kesinti yapacaklarini soylediler bende kabul ettim su an aylik tl kesinti oluyor tl geri iade ediyor
output (category as text):  spor
In [52]:
train_size = train_ds.cardinality().numpy()
print("Train size: ", train_size)
Train size:  15201
In [53]:
val_text_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(val_features.values, tf.string)
)
In [54]:
val_cat_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(val_targets.values, tf.int64),

) 
In [55]:
val_text_ds = val_text_ds_raw.map(prepare_lm_inputs_labels, 
                                  num_parallel_calls=tf.data.experimental.AUTOTUNE)
In [56]:
val_ds = tf.data.Dataset.zip(
    (       val_text_ds,
            val_cat_ds_raw
       )
) 
In [57]:
for X,y in val_ds.take(1):
  print("X.shape: ",X.shape, "y.shape: ", y.shape)
  print("X: ", X)
  print("y: ",y)
  input = " ".join([vocab[_] for _ in np.squeeze(X)])
  output = id_to_category[y.numpy()]
  print("input (review as text): " , input)
  print("output (category as text ): " , output)
X.shape:  (40,) y.shape:  ()
X:  tf.Tensor(
[  546 28145   154  1661    89 23010   109   246  1170   546  3561   867
  1086   115    25    21  1240 24186  6760   198    12    89 14049   391
     3  1031  1362   819    13    15 49918  6300     3     1    14  2404
  4610    12   282  1355], shape=(40,), dtype=int64)
y:  tf.Tensor(25, shape=(), dtype=int64)
input (review as text):  bosch automotiv fazla kesilen fatura odemesinin iadesi yapilmadi gunes bosch car antalya servisine yaklasik ay once verdigimiz kazali aracimiz bize tl fatura kesilerek verildi ve odemesi bizden alindi daha sonra experin yonlendirmesi ve [UNK] ile asil tutarin tl olmasi gerektigi
output (category as text ):  otomotiv
In [58]:
test_text_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(test_features.values, tf.string)
) 
In [59]:
test_cat_ds_raw = tf.data.Dataset.from_tensor_slices(
            tf.cast(test_targets.values, tf.int64),

) 
In [60]:
test_text_ds = test_text_ds_raw.map(prepare_lm_inputs_labels, 
                                  num_parallel_calls=tf.data.experimental.AUTOTUNE)
In [61]:
test_ds = tf.data.Dataset.zip(
    (       test_text_ds,
            test_cat_ds_raw
       )
) 
In [62]:
for X,y in test_ds.take(1):
  print("X.shape: ",X.shape, "y.shape: ", y.shape)
  print("X: ", X)
  print("y: ",y)
  input = " ".join([vocab[_] for _ in np.squeeze(X)])
  output = id_to_category[y.numpy()]
  print("input (review as text): " , input)
  print("output (category as text ): " , output)
X.shape:  (40,) y.shape:  ()
X:  tf.Tensor(
[  548   858  3339  1385   204  1810    48  1816 23804  2168 26274  4967
   188  1347    64    37   237 47546 14805  4779 13020  2425     1 17361
   204 27069   237 10552  4780   211    32   129     1   793     0     0
     0     0     0     0], shape=(40,), dtype=int64)
y:  tf.Tensor(5, shape=(), dtype=int64)
input (review as text):  egitim bilisim agi eba farkli gune ayni ders koyulmasi sinif edebiyat dersi mart pazartesi bugun fakat gecen haftaki dersin aynisini vermissiniz program [UNK] konular farkli cikanlar gecen haftanin aynisi hemen su an [UNK] sevinirim      
output (category as text ):  egitim
In [63]:
test_size = test_ds.cardinality().numpy()
print("Test size: ", test_size)
Test size:  84457
In [64]:
AUTOTUNE=tf.data.experimental.AUTOTUNE

train_ds=train_ds.shuffle(buffer_size=train_size)
train_ds=train_ds.batch(batch_size=batch_size,drop_remainder=True)
train_ds=train_ds.cache()
train_ds = train_ds.prefetch(AUTOTUNE)

val_ds=val_ds.shuffle(buffer_size=train_size)
val_ds=val_ds.batch(batch_size=batch_size,drop_remainder=True)
val_ds=val_ds.cache()
val_ds = val_ds.prefetch(AUTOTUNE)

test_ds=test_ds.shuffle(buffer_size=train_size)
test_ds=test_ds.batch(batch_size=batch_size,drop_remainder=True)
test_ds=test_ds.cache()
test_ds = test_ds.prefetch(AUTOTUNE)
In [65]:
train_ds.element_spec
Out[65]:
(TensorSpec(shape=<unknown>, dtype=tf.int64, name=None),
 TensorSpec(shape=(64,), dtype=tf.int64, name=None))
In [66]:
for X, y in train_ds.take(1):
  print(X.shape, y.shape)
  print("All categories values in this batch: ", y)
  print("\nFirst sample in the batch:")
  print("\tX is: " ,X[0])
  print("\ty is: ", y[0].numpy)
  input = " ".join([vocab[_] for _ in np.squeeze(X[0])])
  output = id_to_category[y[0].numpy()]
  print("\tinput (in text): " , input)
  print("\toutput (in category): " , output)

  print("\nSecond sample in the batch:")
  print("\tX is: " ,X[1])
  print("\ty is: ", y[1].numpy)
  input = " ".join([vocab[_] for _ in np.squeeze(X[1])])
  output = id_to_category[y[1].numpy()]
  print("\tinput (in text): " , input)
  print("\toutput (in category): " , output)
(64, 40) (64,)
All categories values in this batch:  tf.Tensor(
[26 10 28 21 20 10  9  6  3  3 13 27 11 14 22  7 11 11  0  7 28 28 12 25
  6 17  7 29 31 12  0  8 10 10 18  2 17 17 28 21  2  0  6  4 14 19  8 31
 11  2 20 21 23 16 31 15 30  3 18 10  3 23 15  5], shape=(64,), dtype=int64)

First sample in the batch:
	X is:  tf.Tensor(
[ 2626   225    38  4040   886  4189  2223  2017  2626     6   295   749
     3  3478 44278   419  8542   694  3107 52975    53   962  8615    98
   576   540 13573     3 26573  1594     7 44265     9  2626    41  1007
   445    38   135  2981], shape=(40,), dtype=int64)
	y is:  <bound method _EagerTensorBase.numpy of <tf.Tensor: shape=(), dtype=int64, numpy=26>>
	input (in text):  acibadem hastanesi para odakli calisma tarzi calistigim kurum acibadem de butun muayene ve ucretleri karsilamakta normal doktorlari eger bulundugu dalda o hastane bunyesinde baska doktor yoksa prof ve docent farki da karsilaniyor ama acibadem her seferinde benden para talep etmekte
	output (in category):  saglik

Second sample in the batch:
	X is:  tf.Tensor(
[ 4827   381    33   496   100 26130 10532    99    86   174   783    12
  1713    38   783  3311  4827    14   736   944  2061   107  1266    38
 29463   130  1371 26130  5780    51  3417   156    37   136   100   381
  2898     0     0     0], shape=(40,), dtype=int64)
	y is:  <bound method _EagerTensorBase.numpy of <tf.Tensor: shape=(), dtype=int64, numpy=10>>
	input (in text):  tosla parami iade etmiyor gundur enistemin hesabindan mayis gunu kendi hesabima tl gonderdik para hesabima gelmeyince tosla ile iletisime gectim hesaba sadece kendim para yukleyebilecegimi soylediler paranin enistemin hesabina geri gonderilmesini istedim fakat tam gundur parami gondermiyorlar   
	output (in category):  finans
In [67]:
 model_FFN=create_model_FFN()
In [68]:
model_FFN.summary()
Model: "model_FFN"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_1 (InputLayer)        [(None, 40)]              0         
                                                                 
 embedding (Embedding)       (None, 40, 16)            1600000   
                                                                 
 flatten (Flatten)           (None, 640)               0         
                                                                 
 dense (Dense)               (None, 64)                41024     
                                                                 
 dropout (Dropout)           (None, 64)                0         
                                                                 
 dense_1 (Dense)             (None, 32)                2080      
                                                                 
=================================================================
Total params: 1,643,104
Trainable params: 1,643,104
Non-trainable params: 0
_________________________________________________________________
In [69]:
tf.keras.utils.plot_model(model_FFN,show_shapes=True)
Out[69]:
In [70]:
history=model_FFN.fit(train_ds, validation_data=val_ds ,verbose=2, epochs=7)
Epoch 1/7
237/237 - 5s - loss: 3.3375 - sparse_categorical_accuracy: 0.1515 - val_loss: 2.8378 - val_sparse_categorical_accuracy: 0.4387 - 5s/epoch - 21ms/step
Epoch 2/7
237/237 - 3s - loss: 1.8530 - sparse_categorical_accuracy: 0.5863 - val_loss: 1.0538 - val_sparse_categorical_accuracy: 0.8125 - 3s/epoch - 13ms/step
Epoch 3/7
237/237 - 3s - loss: 0.7937 - sparse_categorical_accuracy: 0.8217 - val_loss: 0.6232 - val_sparse_categorical_accuracy: 0.8708 - 3s/epoch - 12ms/step
Epoch 4/7
237/237 - 4s - loss: 0.4169 - sparse_categorical_accuracy: 0.9147 - val_loss: 0.4960 - val_sparse_categorical_accuracy: 0.8810 - 4s/epoch - 15ms/step
Epoch 5/7
237/237 - 4s - loss: 0.2432 - sparse_categorical_accuracy: 0.9527 - val_loss: 0.4490 - val_sparse_categorical_accuracy: 0.8834 - 4s/epoch - 15ms/step
Epoch 6/7
237/237 - 4s - loss: 0.1518 - sparse_categorical_accuracy: 0.9730 - val_loss: 0.4280 - val_sparse_categorical_accuracy: 0.8894 - 4s/epoch - 15ms/step
Epoch 7/7
237/237 - 3s - loss: 0.1042 - sparse_categorical_accuracy: 0.9834 - val_loss: 0.4257 - val_sparse_categorical_accuracy: 0.8912 - 3s/epoch - 15ms/step
In [71]:
plt.plot(history.history['sparse_categorical_accuracy'])
plt.plot(history.history['val_sparse_categorical_accuracy'])
plt.title('model_FFN accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
In [72]:
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model_FFN loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
In [73]:
loss, accuracy = model_FFN.evaluate(test_ds)
print("FFN Test accuracy: ", accuracy)
1319/1319 [==============================] - 3s 1ms/step - loss: 0.4572 - sparse_categorical_accuracy: 0.8869
FFN Test accuracy:  0.8869290351867676
In [74]:
preds = model_FFN.predict(test_ds)
preds = preds.argmax(axis=1)
1319/1319 [==============================] - 2s 2ms/step
In [75]:
actuals = test_ds.unbatch().map(lambda x,y: y)  
actuals=list(actuals.as_numpy_iterator())
In [76]:
print(metrics.classification_report(actuals, preds, digits=4))
              precision    recall  f1-score   support

           0     0.7610    0.8212    0.7900      2707
           1     0.9712    0.9064    0.9377      2457
           2     0.8003    0.8880    0.8419      2731
           3     0.7776    0.8387    0.8070      2560
           4     0.8962    0.8953    0.8958      2769
           5     0.9697    0.9178    0.9431      2617
           6     0.9002    0.8467    0.8726      2726
           7     0.5637    0.8226    0.6689      2379
           8     0.9645    0.9753    0.9699      2757
           9     0.9586    0.8492    0.9006      2235
          10     0.9634    0.9518    0.9576      2739
          11     0.8666    0.8632    0.8649      2603
          12     0.8788    0.9147    0.8964      2686
          13     0.8561    0.8463    0.8512      2264
          14     0.9697    0.9433    0.9563      2680
          15     0.5854    0.7629    0.6625      2682
          16     0.9570    0.9245    0.9405      2769
          17     0.9886    0.9559    0.9720      2724
          18     0.7965    0.8130    0.8047      2508
          19     0.9043    0.8517    0.8772      2718
          20     0.9266    0.9182    0.9224      2751
          21     0.9345    0.7985    0.8611      2734
          22     0.9548    0.8966    0.9248      2660
          23     0.9699    0.9261    0.9475      2572
          24     0.9198    0.8633    0.8907      2751
          25     0.8682    0.8656    0.8669      2649
          26     0.9655    0.8830    0.9224      2693
          27     0.9729    0.9711    0.9720      2665
          28     0.9706    0.8932    0.9303      2660
          29     0.9379    0.9032    0.9202      2592
          30     0.9387    0.9173    0.9279      2623
          31     0.9745    0.9307    0.9521      2755

    accuracy                         0.8869     84416
   macro avg     0.8957    0.8861    0.8890     84416
weighted avg     0.8970    0.8869    0.8901     84416

In [77]:
cm = confusion_matrix(actuals, preds)
cm_df = pd.DataFrame(cm, index = id_to_category.values() ,columns = id_to_category.values())
In [78]:
cm_df
Out[78]:
hizmet-sektoru anne-bebek egitim icecek cep-telefon-kategori mekan-ve-eglence elektronik kucuk-ev-aletleri alisveris beyaz-esya ... saglik kargo-nakliyat mutfak-arac-gerec kamu-hizmetleri etkinlik-ve-organizasyon spor bilgisayar mucevher-saat-gozluk kisisel-bakim-ve-kozmetik internet
hizmet-sektoru 2223 2 11 30 8 2 9 58 0 5 ... 8 5 7 22 3 2 3 15 2 4
anne-bebek 16 2227 3 2 12 0 0 21 0 0 ... 15 0 2 0 4 0 3 3 5 1
egitim 9 0 2425 7 12 2 43 97 7 0 ... 4 0 29 3 1 0 0 11 0 1
icecek 19 1 31 2147 93 0 66 29 0 1 ... 2 5 0 8 2 2 0 1 2 0
cep-telefon-kategori 8 0 19 116 2479 0 21 15 1 1 ... 2 2 8 1 0 2 1 0 1 0
mekan-ve-eglence 21 2 0 2 0 2402 0 14 5 1 ... 4 1 2 11 18 3 7 4 3 2
elektronik 6 0 67 117 77 1 2308 50 3 0 ... 2 0 1 5 0 1 0 0 1 0
kucuk-ev-aletleri 24 0 66 17 10 0 5 1957 37 4 ... 4 6 7 68 0 2 4 2 4 1
alisveris 2 0 3 1 0 0 1 14 2689 1 ... 0 3 1 5 0 0 0 0 0 0
beyaz-esya 32 0 1 20 2 17 7 50 1 1898 ... 3 4 1 5 5 1 16 3 19 1
emlak-ve-insaat 20 0 3 1 1 3 0 15 5 3 ... 0 0 1 6 0 11 0 4 0 0
otomotiv 30 4 15 19 4 2 0 98 1 0 ... 1 1 3 26 0 0 0 22 2 4
enerji 40 2 0 10 0 0 0 8 1 0 ... 3 2 4 0 0 1 5 4 1 0
finans 10 0 0 22 1 1 11 111 7 9 ... 0 2 0 31 6 3 6 1 6 3
giyim 16 1 2 6 0 0 0 19 0 0 ... 0 3 0 12 0 3 0 7 0 1
ulasim 81 9 3 35 20 8 2 36 0 4 ... 11 3 2 16 1 9 3 11 37 6
temizlik 22 3 1 1 0 4 2 63 12 2 ... 0 2 0 12 4 4 0 5 2 3
medya 5 0 1 0 0 0 0 1 0 0 ... 3 0 0 1 0 1 0 5 0 0
mobilya-ev-tekstili 30 15 20 17 7 12 4 35 4 2 ... 8 5 25 7 12 1 6 12 0 0
gida 7 2 175 2 6 0 9 75 0 0 ... 15 0 88 0 0 0 0 4 1 0
turizm 12 3 1 27 5 4 43 14 0 5 ... 0 0 0 5 1 3 5 3 4 1
sigortacilik 89 1 8 23 6 2 3 175 1 11 ... 0 14 2 30 9 5 3 1 16 1
saglik 11 2 13 3 2 0 5 47 0 0 ... 2385 0 11 2 0 0 1 22 2 1
kargo-nakliyat 41 0 1 36 0 1 0 18 1 1 ... 0 2382 0 13 0 0 2 2 1 0
mutfak-arac-gerec 22 2 129 6 1 0 3 45 0 0 ... 17 1 2375 2 0 0 0 3 0 0
kamu-hizmetleri 31 1 9 20 3 0 2 141 4 1 ... 0 11 0 2293 1 17 1 3 3 0
etkinlik-ve-organizasyon 17 11 4 7 2 10 1 91 4 0 ... 3 1 4 5 2378 0 0 3 0 0
spor 6 0 0 0 3 0 1 4 0 0 ... 0 0 0 12 1 2588 0 0 1 1
bilgisayar 6 1 1 58 6 1 8 41 5 22 ... 1 1 2 5 7 0 2376 2 8 1
mucevher-saat-gozluk 35 4 18 1 4 4 0 39 0 3 ... 3 1 6 13 1 1 0 2341 0 0
kisisel-bakim-ve-kozmetik 20 0 0 7 2 1 8 27 0 5 ... 2 0 0 5 8 0 6 0 2406 35
internet 10 0 0 1 0 0 2 64 0 1 ... 2 1 1 17 1 0 0 2 36 2564

32 rows × 32 columns

In [79]:
plt.figure(figsize=(22,22))
ax = sns.heatmap(cm_df/np.sum(cm_df), annot=True, fmt='.1%', cmap='Blues')

ax.set_title('Confusion Matrix\n\n');
ax.set_xlabel('\nPredicted')
ax.set_ylabel('Actual');

ax.xaxis.set_ticklabels(id_to_category.values())
ax.yaxis.set_ticklabels(id_to_category.values())

plt.show()
In [80]:
model_Conv1D=create_model_Conv1D()
In [81]:
model_Conv1D.summary()
Model: "model_Conv1D"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_2 (InputLayer)        [(None, 40)]              0         
                                                                 
 embedding_1 (Embedding)     (None, 40, 16)            1600000   
                                                                 
 conv1d (Conv1D)             (None, 40, 256)           28928     
                                                                 
 conv1d_1 (Conv1D)           (None, 40, 128)           163968    
                                                                 
 conv1d_2 (Conv1D)           (None, 40, 128)           49280     
                                                                 
 max_pooling1d (MaxPooling1D  (None, 20, 128)          0         
 )                                                               
                                                                 
 flatten_1 (Flatten)         (None, 2560)              0         
                                                                 
 dense_2 (Dense)             (None, 64)                163904    
                                                                 
 dropout_1 (Dropout)         (None, 64)                0         
                                                                 
 dense_3 (Dense)             (None, 32)                2080      
                                                                 
=================================================================
Total params: 2,008,160
Trainable params: 2,008,160
Non-trainable params: 0
_________________________________________________________________
In [82]:
tf.keras.utils.plot_model(model_Conv1D,show_shapes=True)
Out[82]:
In [83]:
history=model_Conv1D.fit(train_ds, validation_data=val_ds ,verbose=1, epochs=25)
Epoch 1/25
237/237 [==============================] - 9s 32ms/step - loss: 3.4541 - sparse_categorical_accuracy: 0.0404 - val_loss: 3.3438 - val_sparse_categorical_accuracy: 0.0577
Epoch 2/25
237/237 [==============================] - 8s 32ms/step - loss: 3.2819 - sparse_categorical_accuracy: 0.0716 - val_loss: 3.1423 - val_sparse_categorical_accuracy: 0.0895
Epoch 3/25
237/237 [==============================] - 7s 31ms/step - loss: 3.0869 - sparse_categorical_accuracy: 0.0996 - val_loss: 2.9505 - val_sparse_categorical_accuracy: 0.1400
Epoch 4/25
237/237 [==============================] - 7s 32ms/step - loss: 2.8340 - sparse_categorical_accuracy: 0.1475 - val_loss: 2.6613 - val_sparse_categorical_accuracy: 0.2163
Epoch 5/25
237/237 [==============================] - 7s 31ms/step - loss: 2.4666 - sparse_categorical_accuracy: 0.2452 - val_loss: 2.2390 - val_sparse_categorical_accuracy: 0.3389
Epoch 6/25
237/237 [==============================] - 8s 33ms/step - loss: 2.0171 - sparse_categorical_accuracy: 0.3699 - val_loss: 1.8099 - val_sparse_categorical_accuracy: 0.4874
Epoch 7/25
237/237 [==============================] - 7s 31ms/step - loss: 1.5258 - sparse_categorical_accuracy: 0.5270 - val_loss: 1.5264 - val_sparse_categorical_accuracy: 0.5739
Epoch 8/25
237/237 [==============================] - 7s 31ms/step - loss: 1.1940 - sparse_categorical_accuracy: 0.6324 - val_loss: 1.3651 - val_sparse_categorical_accuracy: 0.6430
Epoch 9/25
237/237 [==============================] - 7s 31ms/step - loss: 0.9673 - sparse_categorical_accuracy: 0.7077 - val_loss: 1.2037 - val_sparse_categorical_accuracy: 0.6929
Epoch 10/25
237/237 [==============================] - 7s 30ms/step - loss: 0.8181 - sparse_categorical_accuracy: 0.7585 - val_loss: 1.1245 - val_sparse_categorical_accuracy: 0.7212
Epoch 11/25
237/237 [==============================] - 7s 31ms/step - loss: 0.6983 - sparse_categorical_accuracy: 0.7900 - val_loss: 1.1038 - val_sparse_categorical_accuracy: 0.7314
Epoch 12/25
237/237 [==============================] - 7s 31ms/step - loss: 0.6122 - sparse_categorical_accuracy: 0.8113 - val_loss: 1.0782 - val_sparse_categorical_accuracy: 0.7596
Epoch 13/25
237/237 [==============================] - 7s 31ms/step - loss: 0.5447 - sparse_categorical_accuracy: 0.8319 - val_loss: 1.0575 - val_sparse_categorical_accuracy: 0.7584
Epoch 14/25
237/237 [==============================] - 7s 31ms/step - loss: 0.5005 - sparse_categorical_accuracy: 0.8460 - val_loss: 1.0472 - val_sparse_categorical_accuracy: 0.7800
Epoch 15/25
237/237 [==============================] - 8s 32ms/step - loss: 0.4440 - sparse_categorical_accuracy: 0.8677 - val_loss: 1.0307 - val_sparse_categorical_accuracy: 0.7927
Epoch 16/25
237/237 [==============================] - 8s 32ms/step - loss: 0.3865 - sparse_categorical_accuracy: 0.8914 - val_loss: 1.0334 - val_sparse_categorical_accuracy: 0.7987
Epoch 17/25
237/237 [==============================] - 8s 32ms/step - loss: 0.3511 - sparse_categorical_accuracy: 0.9047 - val_loss: 1.0151 - val_sparse_categorical_accuracy: 0.8005
Epoch 18/25
237/237 [==============================] - 7s 31ms/step - loss: 0.3213 - sparse_categorical_accuracy: 0.9142 - val_loss: 1.0342 - val_sparse_categorical_accuracy: 0.8023
Epoch 19/25
237/237 [==============================] - 8s 32ms/step - loss: 0.2845 - sparse_categorical_accuracy: 0.9301 - val_loss: 1.0683 - val_sparse_categorical_accuracy: 0.8041
Epoch 20/25
237/237 [==============================] - 7s 32ms/step - loss: 0.2590 - sparse_categorical_accuracy: 0.9335 - val_loss: 1.0712 - val_sparse_categorical_accuracy: 0.8101
Epoch 21/25
237/237 [==============================] - 7s 32ms/step - loss: 0.2344 - sparse_categorical_accuracy: 0.9386 - val_loss: 1.1074 - val_sparse_categorical_accuracy: 0.8101
Epoch 22/25
237/237 [==============================] - 8s 32ms/step - loss: 0.2255 - sparse_categorical_accuracy: 0.9394 - val_loss: 1.1440 - val_sparse_categorical_accuracy: 0.8143
Epoch 23/25
237/237 [==============================] - 7s 31ms/step - loss: 0.2129 - sparse_categorical_accuracy: 0.9420 - val_loss: 1.1124 - val_sparse_categorical_accuracy: 0.8089
Epoch 24/25
237/237 [==============================] - 7s 31ms/step - loss: 0.1983 - sparse_categorical_accuracy: 0.9435 - val_loss: 1.1828 - val_sparse_categorical_accuracy: 0.8167
Epoch 25/25
237/237 [==============================] - 7s 31ms/step - loss: 0.1939 - sparse_categorical_accuracy: 0.9465 - val_loss: 1.1952 - val_sparse_categorical_accuracy: 0.8101
In [84]:
plt.plot(history.history['sparse_categorical_accuracy'])
plt.plot(history.history['val_sparse_categorical_accuracy'])
plt.title('model_Conv1D accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
In [85]:
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.title('model_Conv1D loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'val'], loc='upper left')
plt.show()
In [86]:
model_Conv1D.summary()
Model: "model_Conv1D"
_________________________________________________________________
 Layer (type)                Output Shape              Param #   
=================================================================
 input_2 (InputLayer)        [(None, 40)]              0         
                                                                 
 embedding_1 (Embedding)     (None, 40, 16)            1600000   
                                                                 
 conv1d (Conv1D)             (None, 40, 256)           28928     
                                                                 
 conv1d_1 (Conv1D)           (None, 40, 128)           163968    
                                                                 
 conv1d_2 (Conv1D)           (None, 40, 128)           49280     
                                                                 
 max_pooling1d (MaxPooling1D  (None, 20, 128)          0         
 )                                                               
                                                                 
 flatten_1 (Flatten)         (None, 2560)              0         
                                                                 
 dense_2 (Dense)             (None, 64)                163904    
                                                                 
 dropout_1 (Dropout)         (None, 64)                0         
                                                                 
 dense_3 (Dense)             (None, 32)                2080      
                                                                 
=================================================================
Total params: 2,008,160
Trainable params: 2,008,160
Non-trainable params: 0
_________________________________________________________________
In [87]:
loss, accuracy = model_Conv1D.evaluate(test_ds)
print("CONV1D Test accuracy: ", accuracy)
1319/1319 [==============================] - 11s 8ms/step - loss: 1.1947 - sparse_categorical_accuracy: 0.8053
CONV1D Test accuracy:  0.805333137512207
In [88]:
preds = model_Conv1D.predict(test_ds)
preds = preds.argmax(axis=1)
1319/1319 [==============================] - 11s 8ms/step
In [89]:
actuals = test_ds.unbatch().map(lambda x,y: y)  
actuals=list(actuals.as_numpy_iterator())
In [90]:
print(metrics.classification_report(actuals, preds, digits=4))
              precision    recall  f1-score   support

           0     0.6450    0.8142    0.7198      2707
           1     0.8692    0.8221    0.8450      2457
           2     0.7263    0.7364    0.7313      2731
           3     0.8127    0.6375    0.7145      2560
           4     0.8850    0.8592    0.8719      2769
           5     0.8965    0.8475    0.8713      2617
           6     0.8894    0.7197    0.7956      2726
           7     0.5846    0.5956    0.5900      2379
           8     0.9518    0.8168    0.8792      2757
           9     0.7972    0.8018    0.7995      2235
          10     0.9277    0.9043    0.9159      2739
          11     0.7254    0.6262    0.6722      2603
          12     0.8982    0.8213    0.8580      2686
          13     0.8595    0.7350    0.7924      2264
          14     0.8477    0.8720    0.8597      2680
          15     0.3741    0.7979    0.5094      2682
          16     0.9417    0.8462    0.8914      2769
          17     0.8974    0.9633    0.9292      2724
          18     0.7938    0.7628    0.7780      2508
          19     0.8330    0.8021    0.8172      2718
          20     0.8914    0.8710    0.8810      2751
          21     0.6235    0.7977    0.6999      2734
          22     0.8067    0.8271    0.8168      2660
          23     0.8980    0.8767    0.8873      2572
          24     0.8646    0.8288    0.8463      2751
          25     0.8303    0.7350    0.7797      2649
          26     0.8697    0.8530    0.8613      2693
          27     0.9640    0.9343    0.9489      2665
          28     0.9110    0.8008    0.8523      2660
          29     0.9208    0.7936    0.8525      2592
          30     0.8378    0.7678    0.8013      2623
          31     0.8775    0.8475    0.8623      2755

    accuracy                         0.8053     84416
   macro avg     0.8266    0.8036    0.8103     84416
weighted avg     0.8276    0.8053    0.8116     84416

In [91]:
cm = confusion_matrix(actuals, preds)
cm_df = pd.DataFrame(cm, index = id_to_category.values() ,
                     columns = id_to_category.values())
In [92]:
cm_df
Out[92]:
hizmet-sektoru anne-bebek egitim icecek cep-telefon-kategori mekan-ve-eglence elektronik kucuk-ev-aletleri alisveris beyaz-esya ... saglik kargo-nakliyat mutfak-arac-gerec kamu-hizmetleri etkinlik-ve-organizasyon spor bilgisayar mucevher-saat-gozluk kisisel-bakim-ve-kozmetik internet
hizmet-sektoru 2204 0 1 6 10 4 7 18 0 5 ... 9 1 1 10 6 0 6 2 10 6
anne-bebek 11 2020 12 2 0 13 0 47 0 182 ... 3 0 17 2 3 1 2 0 7 17
egitim 41 121 2011 17 10 10 19 48 15 12 ... 9 1 99 7 8 0 5 1 4 10
icecek 25 3 36 1632 78 1 79 35 3 0 ... 299 1 4 37 11 1 0 1 1 8
cep-telefon-kategori 22 2 66 56 2379 0 89 4 16 0 ... 3 3 12 3 2 0 3 1 3 1
mekan-ve-eglence 33 0 1 2 0 2218 0 17 0 3 ... 2 3 2 17 14 1 13 24 4 16
elektronik 13 2 202 127 131 0 1962 20 64 1 ... 10 0 7 12 12 0 0 2 0 0
kucuk-ev-aletleri 52 6 13 10 0 27 1 1417 5 55 ... 17 0 13 59 21 2 1 1 10 31
alisveris 9 11 199 37 36 0 11 50 2252 0 ... 16 3 3 6 3 0 0 0 1 1
beyaz-esya 19 1 0 1 0 21 5 71 0 1792 ... 7 2 12 2 3 5 6 2 52 39
emlak-ve-insaat 35 0 0 3 1 4 0 5 0 0 ... 0 4 1 3 5 2 0 41 7 0
otomotiv 147 1 0 0 1 2 0 7 0 2 ... 0 3 1 0 1 1 5 1 11 4
enerji 85 0 0 0 0 2 0 4 0 1 ... 3 2 3 5 1 0 2 1 6 4
finans 37 1 0 3 1 7 6 83 1 8 ... 3 24 3 8 32 6 59 8 10 4
giyim 12 0 0 0 0 3 0 7 1 6 ... 0 0 1 0 0 2 12 0 19 4
ulasim 118 4 5 17 9 14 2 38 2 7 ... 13 3 6 22 4 1 3 2 39 8
temizlik 30 2 1 36 5 29 6 18 3 1 ... 23 4 5 52 6 4 3 4 3 24
medya 4 2 0 0 0 0 1 2 0 9 ... 1 1 0 0 1 3 1 0 7 2
mobilya-ev-tekstili 109 14 13 2 5 5 2 21 0 5 ... 3 59 10 4 17 2 2 24 4 5
gida 9 82 115 5 5 3 2 109 2 24 ... 20 0 87 13 11 0 2 1 0 2
turizm 28 1 0 9 12 8 8 11 0 0 ... 9 0 2 20 20 0 1 12 0 1
sigortacilik 93 0 0 0 0 9 0 19 0 8 ... 1 37 4 0 3 3 24 2 28 11
saglik 23 0 4 14 0 1 1 142 0 11 ... 2200 2 9 32 8 0 1 3 4 26
kargo-nakliyat 32 2 1 1 0 5 1 5 0 0 ... 2 2255 3 2 4 12 30 3 9 0
mutfak-arac-gerec 16 40 85 4 0 7 0 25 0 64 ... 15 5 2280 11 2 9 6 1 25 27
kamu-hizmetleri 35 1 3 13 2 25 1 111 1 2 ... 42 2 4 1947 37 4 0 13 4 17
etkinlik-ve-organizasyon 49 1 1 5 0 0 1 22 1 1 ... 6 10 0 40 2297 1 0 25 1 2
spor 6 4 0 0 1 9 0 1 0 25 ... 0 0 2 5 3 2490 7 0 35 2
bilgisayar 31 1 0 1 1 4 1 14 0 2 ... 2 61 3 3 1 19 2130 2 35 7
mucevher-saat-gozluk 26 1 0 2 1 3 1 22 0 2 ... 1 22 2 7 104 0 0 2057 0 2
kisisel-bakim-ve-kozmetik 37 0 0 0 0 8 0 10 0 9 ... 2 3 6 0 0 12 14 0 2014 45
internet 26 1 0 3 0 32 0 21 0 11 ... 6 0 35 16 1 2 0 0 51 2335

32 rows × 32 columns

In [93]:
plt.figure(figsize=(22,22))
ax = sns.heatmap(cm_df/np.sum(cm_df), annot=True, fmt='.1%', cmap='Blues')

ax.set_title('Confusion Matrix\n\n');
ax.set_xlabel('\nPredicted')
ax.set_ylabel('Actual');

ax.xaxis.set_ticklabels(id_to_category.values())
ax.yaxis.set_ticklabels(id_to_category.values())

## Display the visualization of the Confusion Matrix.
plt.show()
In [94]:
# End to End Modelleri Oluşturma
In [95]:
E2E_CONV1D = tf.keras.Sequential([
  vectorize_layer,
  model_Conv1D,
  layers.Activation('softmax')
])

E2E_CONV1D.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), 
    optimizer="adam", metrics=['accuracy']
)

E2E_FFN = tf.keras.Sequential([
  vectorize_layer,
  model_FFN,
  layers.Activation('softmax')
])

E2E_FFN.compile(
    loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=False), 
    optimizer="adam", metrics=['accuracy']
)
In [96]:
loss, accuracy = E2E_CONV1D.evaluate(test_features, test_targets)
print("CONV1D Test accuracy: ",accuracy)
loss, accuracy = E2E_FFN.evaluate(test_features, test_targets)
print("FFN Test accuracy: ",accuracy)
2640/2640 [==============================] - 24s 9ms/step - loss: 1.1947 - accuracy: 0.8053
CONV1D Test accuracy:  0.8053210377693176
2640/2640 [==============================] - 9s 3ms/step - loss: 0.4572 - accuracy: 0.8869
FFN Test accuracy:  0.8869484066963196
In [97]:
tf.keras.models.save_model(E2E_CONV1D, 'MCTC_Conv1D_E2E')
tf.keras.models.save_model(E2E_FFN, 'MCTC_FFN_E2E')
WARNING:absl:Found untraced functions such as _update_step_xla, _jit_compiled_convolution_op, _jit_compiled_convolution_op, _jit_compiled_convolution_op, _update_step_xla while saving (showing 5 of 5). These functions will not be directly callable after loading.
INFO:tensorflow:Assets written to: MCTC_Conv1D_E2E\assets
INFO:tensorflow:Assets written to: MCTC_Conv1D_E2E\assets
WARNING:absl:Found untraced functions such as _update_step_xla, _update_step_xla while saving (showing 2 of 2). These functions will not be directly callable after loading.
INFO:tensorflow:Assets written to: MCTC_FFN_E2E\assets
INFO:tensorflow:Assets written to: MCTC_FFN_E2E\assets
In [98]:
E2E_CONV1D= tf.keras.models.load_model('MCTC_Conv1D_E2E')
E2E_FFN= tf.keras.models.load_model('MCTC_FFN_E2E')
In [99]:
examples = [
  "Bir fenomen aracılığı ile Yalova Terma City otel'den arandık. Tatil kazandınız buyurun 16 ocakta gelin dediler. Gittik (2 küçük çocuk, eşim ve annem ), bizi y** adlı kişi karşıladı. Tanıtım yapacağız 4 saat dedi. Daha odamıza bile geçemeden, dinlemeye fırsat vermeden bize oteli gezdirmeye başladılar. Gürültülü, müzik sesli, havasız, kalabalık (Corona olduğu dönemde) bir salonda bize tapulu 1 haftalık arsa sattılar. (psikolojik baskı ile) Tabi o yorgunlukla (amaçları da bu zaten) dinlenmeden bize otelin her detayını anlattılar. Tapumuzu almadan para istediler, güvendik aldık. IBAN numarası otele ait olmayan şahsa 30 bin tl ödedik. 1 gün sonra tapu işlemleri yapılacaktı istemiyoruz tapu, tatil dedik. Kabul etmiyorlar, paramızı vermiyorlar. Ayrıca annemin kaldığı odada ısıtma sistemi çalışmıyordu, çocuk havuzu aşırı pisti, kadınlara ait termal havuz kapalı idi, odada telefon çalışmıyordu ya da bilerek sessize alıyorlar ilgilenmemek için.",
  "5 yıl kullandığım buzdolabım buzluktan şu akıtmaya başladı. Servis geldi içini boşaltın. Lastiklerinden hava alıyor sıcak suyla lastikleri yıkayın dediler. Denileni yaptım. 1 sene olmadan tekrar akıtmaya başladı",
  "Hepsiburada'dan esofman takimi aldık. 18 ocakta yola çıktı ve teslim edildi gözüküyor. Teslim adresi kayınpederimin dükkandı. Ben elemanlar aldı diye düşündüm. Fakat birkaç gün geçti getiren olmadı. Sorunca da kimsenin teslim almadığını öğrendim. Lütfen kargomuzu kime teslim ettiğinizi öğrenin, o gün dağıtım yapan kuryenize sorabilirsiniz. Gereğinin yapılacağını umuyorum, kızıma aldığım bir hediyeydi üzgünüm.",
  "Bimcell tarafıma mesaj atıp 6GB internet Hediye! Evet yazıp 3121'e göndererek kampanyaya katilin,3 gün içinde 30 TL'ye Dost Orta Paket almanız karşılığında haftalık 6GB cepten internet kazanın! Şeklinde mesaj attı dediklerini yerine getirdim paketi yaptım 3121 e Evet yazarak mesaj attım ancak 24.01.2022 de yaptığım işlem hala gerçekleşmedi hediye 6 GB hattıma tanımlanmadı",
  "Instagram'da gözlük marketi hesabı sattığı kalitesiz ürünü geri almıyor. Gözlük çok kötü. Saplar oyuncak desen değil. Oyuncakçıdan alsam çok daha kaliteli olurdu. Bir yazdım iade edebilirsiniz diyor. Sonra yok efendim iademiz yok diyor.",
  "Tamamlayıcı sağlık sigortamı iptal etmek istiyorum fakat ne bankadan ne NN SİGORTA'dan bir tek muhatap bile bulamıyorum. Telefonda dakikalarca tuşlama yapıp bekletiliyor kimsenin cevap verdiği yok. Zaman kaybından başka bir şey değil! İletişim kurabileceğim biri tarafından aranmak istiyorum",
  "Selamlar TOKİ ve emlak yönetimden şikayetimiz var. Kastamonu merkez örencik TOKİ 316 konut 3 gündür kömür gelmedi bir çok blokta kömür bitmiş durumda bu kış zamanında eksi 8 ila 15 derecede yaşlılar hastalar çocuklar bütün herkesi mağdur ettiler. Emlak yönetim 734.60 ton kömür anlaşması yapmış onu da geç yaptığı için zaten yüksek maliyet çıkarmıştı yeni fiyat güncellemesi yapacakmış örneğin bana 6.160 TL nin üzerine fiyat eklenecekmiş bu işi yapan sorumlu kişi veya kişilerin zamanında tedbir almamasının cezasını TOKİ de oturan insanlar çekiyor ya sistem ya da kişiler hatalı"
]

predictions=E2E_CONV1D.predict(examples)
for pred in predictions:
  print(id_to_category[np.argmax(pred)])
predictions=E2E_FFN.predict(examples)
for pred in predictions:
  print(id_to_category[np.argmax(pred)])
1/1 [==============================] - 0s 132ms/step
internet
otomotiv
internet
beyaz-esya
emlak-ve-insaat
mucevher-saat-gozluk
emlak-ve-insaat
1/1 [==============================] - 0s 92ms/step
turizm
beyaz-esya
internet
internet
internet
sigortacilik
emlak-ve-insaat
In [100]:
APP = gr.Interface(
        fn=classify,
inputs=gr.inputs.Textbox(lines=5,label="Yorum Girişi",placeholder="SINIFLANDIRMA YAPMAK İSTEDİĞİNİZ YORUMU BURAYA YAZINIZ VEYA AŞAĞIDAKİ ÖRNEKLERDEN SEÇİNİZ"),
outputs=gr.outputs.Textbox(label="Sınıflandırma Sonucu Kategori"),
examples=examples)
APP.launch()
Running on local URL:  http://127.0.0.1:7860

To create a public link, set `share=True` in `launch()`.
Out[100]:

In [ ]: